<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量导入用户"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div class="import-dialog">
      <!-- 步骤条 -->
      <el-steps :active="currentStep" finish-status="success" class="import-steps">
        <el-step title="下载模板" />
        <el-step title="上传文件" />
        <el-step title="数据预览" />
        <el-step title="导入完成" />
      </el-steps>
      
      <!-- 步骤1: 下载模板 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="template-download">
          <div class="download-icon">
            <el-icon size="48"><Download /></el-icon>
          </div>
          <h3>下载导入模板</h3>
          <p>请先下载用户导入模板，按照模板格式填写用户数据</p>
          
          <div class="template-info">
            <h4>模板说明：</h4>
            <ul>
              <li>用户名：必填，2-20个字符，不能重复</li>
              <li>邮箱：必填，有效的邮箱地址</li>
              <li>手机号：必填，11位手机号码</li>
              <li>密码：选填，不填写则使用默认密码</li>
              <li>部门：选填，用户所属部门</li>
              <li>角色：选填，多个角色用逗号分隔</li>
            </ul>
          </div>
          
          <div class="template-actions">
            <el-button type="primary" @click="downloadTemplate">
              <el-icon><Download /></el-icon>
              下载Excel模板
            </el-button>
            <el-button @click="downloadSample">
              <el-icon><Document /></el-icon>
              下载示例数据
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 步骤2: 上传文件 -->
      <div v-if="currentStep === 1" class="step-content">
        <div class="file-upload">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls"
            :limit="1"
          >
            <div class="upload-content">
              <el-icon class="el-icon--upload" size="67"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件，且不超过 10MB
              </div>
            </div>
          </el-upload>
          
          <div v-if="uploadFile" class="file-info">
            <div class="file-item">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ uploadFile.name }}</span>
              <span class="file-size">{{ formatFileSize(uploadFile.size) }}</span>
              <el-button type="danger" size="small" circle @click="removeFile">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 步骤3: 数据预览 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="data-preview">
          <div class="preview-header">
            <h3>数据预览</h3>
            <div class="preview-stats">
              <el-tag type="success">总计: {{ previewData.length }}</el-tag>
              <el-tag type="primary">有效: {{ validCount }}</el-tag>
              <el-tag type="danger">错误: {{ errorCount }}</el-tag>
            </div>
          </div>
          
          <el-table 
            :data="previewData" 
            border 
            max-height="300"
            :row-class-name="getRowClassName"
          >
            <el-table-column prop="rowNumber" label="行号" width="60" />
            <el-table-column prop="username" label="用户名" width="120">
              <template #default="{ row }">
                <span :class="{ 'error-text': row.errors?.username }">
                  {{ row.username }}
                </span>
                <el-tooltip v-if="row.errors?.username" :content="row.errors.username">
                  <el-icon class="error-icon"><Warning /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="180">
              <template #default="{ row }">
                <span :class="{ 'error-text': row.errors?.email }">
                  {{ row.email }}
                </span>
                <el-tooltip v-if="row.errors?.email" :content="row.errors.email">
                  <el-icon class="error-icon"><Warning /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="120">
              <template #default="{ row }">
                <span :class="{ 'error-text': row.errors?.phone }">
                  {{ row.phone }}
                </span>
                <el-tooltip v-if="row.errors?.phone" :content="row.errors.phone">
                  <el-icon class="error-icon"><Warning /></el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="部门" width="100" />
            <el-table-column prop="roles" label="角色" width="120" />
            <el-table-column label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.hasError ? 'danger' : 'success'" size="small">
                  {{ row.hasError ? '错误' : '正常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="errorCount > 0" class="error-summary">
            <el-alert
              title="数据验证失败"
              :description="`发现 ${errorCount} 条错误数据，请修正后重新上传`"
              type="error"
              show-icon
            />
          </div>
        </div>
      </div>
      
      <!-- 步骤4: 导入完成 -->
      <div v-if="currentStep === 3" class="step-content">
        <div class="import-result">
          <div class="result-icon">
            <el-icon size="64" color="#67C23A"><SuccessFilled /></el-icon>
          </div>
          <h3>导入完成</h3>
          <div class="result-stats">
            <div class="stat-item">
              <div class="stat-number">{{ importResult.total }}</div>
              <div class="stat-label">总计</div>
            </div>
            <div class="stat-item">
              <div class="stat-number success">{{ importResult.success }}</div>
              <div class="stat-label">成功</div>
            </div>
            <div class="stat-item">
              <div class="stat-number error">{{ importResult.failed }}</div>
              <div class="stat-label">失败</div>
            </div>
          </div>
          
          <div v-if="importResult.errors.length > 0" class="error-list">
            <h4>失败记录：</h4>
            <el-scrollbar max-height="150px">
              <div v-for="error in importResult.errors" :key="error.row" class="error-item">
                第 {{ error.row }} 行：{{ error.message }}
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button 
          v-if="currentStep < 3" 
          type="primary" 
          @click="nextStep"
          :disabled="!canNext"
          :loading="processing"
        >
          {{ currentStep === 2 ? '开始导入' : '下一步' }}
        </el-button>
        <el-button v-if="currentStep === 3" type="primary" @click="handleFinish">
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Download, Document, UploadFilled, Close, Warning, SuccessFilled 
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: Boolean
})

const emit = defineEmits(['update:visible', 'success'])

const uploadRef = ref()
const currentStep = ref(0)
const uploadFile = ref(null)
const previewData = ref([])
const processing = ref(false)
const importResult = ref({
  total: 0,
  success: 0,
  failed: 0,
  errors: []
})

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const validCount = computed(() => {
  return previewData.value.filter(row => !row.hasError).length
})

const errorCount = computed(() => {
  return previewData.value.filter(row => row.hasError).length
})

const canNext = computed(() => {
  switch (currentStep.value) {
    case 0:
      return true
    case 1:
      return uploadFile.value !== null
    case 2:
      return errorCount.value === 0
    default:
      return false
  }
})

const downloadTemplate = () => {
  // 模拟下载模板
  ElMessage.success('模板下载成功')
}

const downloadSample = () => {
  // 模拟下载示例
  ElMessage.success('示例数据下载成功')
}

const handleFileChange = (file) => {
  uploadFile.value = file.raw
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return false // 阻止自动上传
}

const removeFile = () => {
  uploadFile.value = null
  uploadRef.value?.clearFiles()
}

const formatFileSize = (size) => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  return (size / 1024 / 1024).toFixed(1) + ' MB'
}

const parseExcelFile = async () => {
  // 模拟解析Excel文件
  processing.value = true
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 模拟解析后的数据
    previewData.value = [
      {
        rowNumber: 2,
        username: 'user001',
        email: 'user001@example.com',
        phone: '13800138001',
        department: '技术部',
        roles: '普通用户',
        hasError: false,
        errors: {}
      },
      {
        rowNumber: 3,
        username: 'user002',
        email: 'invalid-email',
        phone: '138001380',
        department: '运营部',
        roles: '普通用户',
        hasError: true,
        errors: {
          email: '邮箱格式不正确',
          phone: '手机号格式不正确'
        }
      },
      {
        rowNumber: 4,
        username: 'user003',
        email: 'user003@example.com',
        phone: '13800138003',
        department: '销售部',
        roles: '普通用户',
        hasError: false,
        errors: {}
      }
    ]
  } finally {
    processing.value = false
  }
}

const executeImport = async () => {
  processing.value = true
  
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟导入结果
    const validData = previewData.value.filter(row => !row.hasError)
    importResult.value = {
      total: previewData.value.length,
      success: validData.length,
      failed: previewData.value.length - validData.length,
      errors: previewData.value
        .filter(row => row.hasError)
        .map(row => ({
          row: row.rowNumber,
          message: Object.values(row.errors).join(', ')
        }))
    }
    
    ElMessage.success('用户导入完成')
  } finally {
    processing.value = false
  }
}

const nextStep = async () => {
  if (currentStep.value === 1) {
    await parseExcelFile()
  } else if (currentStep.value === 2) {
    await executeImport()
  }
  currentStep.value++
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const getRowClassName = ({ row }) => {
  return row.hasError ? 'error-row' : ''
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleFinish = () => {
  emit('success', importResult.value)
  dialogVisible.value = false
}

const handleClosed = () => {
  currentStep.value = 0
  uploadFile.value = null
  previewData.value = []
  processing.value = false
  importResult.value = {
    total: 0,
    success: 0,
    failed: 0,
    errors: []
  }
  uploadRef.value?.clearFiles()
}
</script>

<style scoped>
.import-dialog {
  min-height: 400px;
}

.import-steps {
  margin-bottom: 30px;
}

.step-content {
  min-height: 300px;
}

.template-download {
  text-align: center;
  padding: 20px;
}

.download-icon {
  color: #4f46e5;
  margin-bottom: 16px;
}

.template-download h3 {
  font-size: 20px;
  color: #1f2937;
  margin-bottom: 8px;
}

.template-download p {
  color: #6b7280;
  margin-bottom: 24px;
}

.template-info {
  text-align: left;
  max-width: 500px;
  margin: 0 auto 24px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.template-info h4 {
  color: #374151;
  margin-bottom: 12px;
}

.template-info ul {
  color: #6b7280;
  margin: 0;
  padding-left: 20px;
}

.template-info li {
  margin-bottom: 4px;
}

.template-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.file-upload {
  padding: 20px;
}

.upload-demo {
  width: 100%;
}

.upload-content {
  padding: 40px 0;
}

.file-info {
  margin-top: 16px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.file-name {
  flex: 1;
  font-weight: 500;
  color: #374151;
}

.file-size {
  color: #6b7280;
  font-size: 14px;
}

.data-preview {
  padding: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.preview-header h3 {
  margin: 0;
  color: #1f2937;
}

.preview-stats {
  display: flex;
  gap: 8px;
}

.error-text {
  color: #ef4444;
}

.error-icon {
  color: #ef4444;
  margin-left: 4px;
}

.error-summary {
  margin-top: 16px;
}

.import-result {
  text-align: center;
  padding: 40px 20px;
}

.result-icon {
  margin-bottom: 16px;
}

.import-result h3 {
  color: #1f2937;
  margin-bottom: 24px;
}

.result-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-number.success {
  color: #10b981;
}

.stat-number.error {
  color: #ef4444;
}

.stat-label {
  color: #6b7280;
  font-size: 14px;
}

.error-list {
  max-width: 500px;
  margin: 0 auto;
  text-align: left;
}

.error-list h4 {
  color: #374151;
  margin-bottom: 12px;
}

.error-item {
  padding: 8px 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 4px;
  color: #dc2626;
  font-size: 14px;
  margin-bottom: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格行样式 */
:deep(.error-row) {
  background-color: #fef2f2;
}

/* 上传组件样式 */
:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s ease;
}

:deep(.el-upload-dragger:hover) {
  border-color: #4f46e5;
  background: #f8fafc;
}

:deep(.el-upload-dragger.is-dragover) {
  border-color: #4f46e5;
  background: #eef2ff;
}

/* 步骤条样式 */
:deep(.el-steps) {
  margin-bottom: 30px;
}

:deep(.el-step__title) {
  font-weight: 500;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8fafc;
  color: #374151;
  font-weight: 600;
}

/* 滚动条样式 */
:deep(.el-scrollbar__wrap) {
  border-radius: 4px;
}

/* 警告框样式 */
:deep(.el-alert) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .preview-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .result-stats {
    gap: 20px;
  }
}
</style>
